package com.palm.vue.integration;

import com.palm.vue.MJsUtil;
import com.palm.vue.Vue3Compressor;
import com.palm.vue.VueCompressor;
import com.palm.vue.VueResourceLoader;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.web.staticfiles.StaticMappings;

import java.io.IOException;
import java.net.URL;
import java.util.Objects;

/**
 * ，
 */
public class JsTransformHandler implements Handler {
    /**
     *
     * @param ctx
     * @throws Throwable
     */
    @Override
    public void handle(Context ctx) throws Throwable {
        if(ctx.getHandled()||ctx.getRendered()){
            return;
        }
        String path=ctx.path();
        //找到需要转换的原文件
        Transformer tf=null;
        URL url=null;
       for(Transformer it:Transformer.values()){
           url=it.find(path);
           if(url!=null){
               tf=it;
               break;
           }
       }
        if(url==null){
            ctx.status(404);
            return;
        }

        ctx.contentType("application/javascript");
        //进行转换
        String data=tf.transform(url,path);
        try {
            ctx.output(data);
        }catch (Exception e){

        }
       // ctx.output(tf.transform(url,path));
        ctx.setHandled(true);
    }
    enum Transformer{
        MJS{
            @Override
            public URL find(String path) throws Exception {
                String newPath=path.replaceFirst("\\.js",".mjs");
                return StaticMappings.find(newPath);
            }
            @Override
            public String transform(URL url,String path) throws Exception {
                return MJsUtil.toAmd(loadSource(url));
            }
        },VUE{
            @Override
            public URL find(String path) throws Exception {
                String newPath=path.replaceFirst("\\.js",".vue");
                URL url= StaticMappings.find(newPath);
                return url;
            }
            @Override
            public String transform(URL url,String path) throws Exception {
                return Objects.equals("2",XPluginImp.vueVersion)?
                        new VueCompressor().compile(loadSource(url),path):
                        new Vue3Compressor().compile(loadSource(url),path);
            }
        };
        public abstract URL find(String path) throws Exception;
        public abstract String transform(URL url,String path) throws Exception;
        protected String loadSource(URL url) throws IOException {
          return VueResourceLoader.loadText(url.openStream());
        }
    }
}
